import streamlit as st
import sys
import os
import re
import json
from transformers import AutoModel, AutoTokenizer
from natsort import natsorted
from langchain_community.chat_models import ChatZhipuAI
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage
from langchain.output_parsers import StructuredOutputParser, ResponseSchema
from langchain_core.prompts import PromptTemplate

from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.image.exceptions import UnrecognizedImageError  
from PIL import Image

# app.py
import tempfile
from typing import Optional
from demo import (
    reduce_frame,
    extract_i_frames,
    OCR_i_frames,
    AI_extract_questions,
    json2word,
    cleanup
)

def main():
    st.title("📚 教学视频习题提取系统")
    #ffmpeg -i 17地形图的判读微课视频.mp4 -vf "fps17" -c:v libx264 -preset fast -crf 23 -g 32 -an -profile:v high -pixfmt yuv420p -movflags faststart -y OUTPUT.mp4

    # 文件上传
    video_file = st.file_uploader("上传教学视频", type=["mp4", "avi", "mov"])
    #cd C:\Users\zcl\Desktop\testdemo\1
    #streamlit run app.py --server.maxUploadSize=2048
    # API密钥输入： 34e4250edb1cc63dfde749a7c83fbbc1.2RbubnzAdoUcBmxM
    api_key = st.text_input("智谱AI API密钥", type="password")
    
    # 参数设置
    with st.expander("高级设置"):
        #帧率说明
        target_framerate = st.slider("目标帧率", 10, 20, 17)
        ocr_model = st.selectbox("OCR模型", ["ucaslcl/GOT-OCR2_0"])
    
    if st.button("开始处理") and video_file and api_key:
        try:
            with tempfile.TemporaryDirectory() as TEMP_DIR:
                # 保存上传的视频
                video_path = os.path.join(TEMP_DIR, video_file.name)
                with open(video_path, "wb") as f:
                    f.write(video_file.getbuffer())
                
                # 显示处理进度
                progress_bar = st.progress(0)
                status_msg = st.empty()
                
                cleanup()

                # 处理流程
                status_msg.info("🔄 正在对视频进行预处理...")
                reduce_frame(video_path, framerate=target_framerate)
                progress_bar.progress(20)
                
                status_msg.info("🎞️ 正在提取关键帧...")
                extract_i_frames("cut.mp4")
                progress_bar.progress(40)
                
                #时间很长请等待
                status_msg.info("🔍 OCR识别中...请耐心等待5-10分钟哦")
                OCR_i_frames()
                progress_bar.progress(60)
                
                status_msg.info("🧠 AI分析习题内容...")
                AI_extract_questions(api_key)
                progress_bar.progress(80)
                
                status_msg.info("📄 生成Word文档...")
                output_path = json2word()
                progress_bar.progress(100)
                
                #清除temp文件
                cleanup()

                # 结果展示
                st.success("处理完成！")
                with open(output_path, "rb") as f:
                    st.download_button(
                        "下载习题文档", 
                        f, 
                        file_name=os.path.basename(output_path),
                        mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
                    )
                
        except ImportError as e:
            st.error(f"模块导入错误：{str(e)}")
        except FileNotFoundError as e:
            st.error(f"文件未找到：{e.filename}")
        except Exception as e:
            st.error(f"处理失败: {str(e)}")
            st.exception(e)

if __name__ == "__main__":
    main()